<template>
  <div class="electricity-trend-card">
    <div class="card-header">
      <div class="title">
        <span>用电量趋势</span>
        <el-tooltip content="用电量趋势统计" placement="top">
          <el-icon><QuestionFilled /></el-icon>
        </el-tooltip>
      </div>
      <div class="time-selectors">
        <el-radio-group v-model="timeType" size="small" @change="handleTypeChange">
          <el-radio-button label="year">年</el-radio-button>
          <el-radio-button label="month">月</el-radio-button>
          <el-radio-button label="day">日</el-radio-button>
          <el-radio-button label="hour">小时</el-radio-button>
        </el-radio-group>
      </div>
    </div>
    <div class="chart-container">
      <div ref="chartRef" style="width: 100%; height: 300px"></div>
      <div v-if="loading" class="loading-overlay">
        <el-loading></el-loading>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, computed } from 'vue'
import { QuestionFilled } from '@element-plus/icons-vue'
import { getElectricityTrend } from '@/api/apartment/record'
import * as echarts from 'echarts'

const chartRef = ref(null)
const chartInstance = ref(null)
const loading = ref(false)
const timeType = ref('day')
const trendData = ref([])

// 计算开始和结束时间
const dateRange = computed(() => {
  const now = new Date()
  let startDate, endDate
  
  switch (timeType.value) {
    case 'hour':
      // 最近24小时
      startDate = new Date(now)
      startDate.setHours(now.getHours() - 24)
      endDate = now
      break
    case 'day':
      // 最近30天
      startDate = new Date(now)
      startDate.setDate(now.getDate() - 30)
      endDate = now
      break
    case 'month':
      // 最近12个月
      startDate = new Date(now)
      startDate.setMonth(now.getMonth() - 12)
      endDate = now
      break
    case 'year':
      // 最近5年
      startDate = new Date(now)
      startDate.setFullYear(now.getFullYear() - 5)
      endDate = now
      break
  }
  
  return {
    startDate: formatDate(startDate),
    endDate: formatDate(endDate)
  }
})

// 格式化日期为 "yyyy-MM-dd HH:mm:ss"
function formatDate(date) {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 处理时间类型变化
function handleTypeChange() {
  fetchTrendData()
}

// 获取趋势数据
function fetchTrendData() {
  loading.value = true
  
  const params = {
    type: timeType.value,
    startDate: dateRange.value.startDate,
    endDate: dateRange.value.endDate
  }
  
  getElectricityTrend(params).then(res => {
    if (res.code === 200) {
      trendData.value = res.data.data || []
      renderChart()
    }
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

// 初始化图表
function initChart() {
  if (chartInstance.value) {
    chartInstance.value.dispose()
  }
  
  chartInstance.value = echarts.init(chartRef.value)
  
  window.addEventListener('resize', resizeChart)
  
  fetchTrendData()
}

// 格式化横坐标标签
function formatAxisLabel(label, type) {
  if (!label) return ''
  
  switch (type) {
    case 'hour':
      // 处理小时数据，仅显示小时和分钟
      if (label.includes(' ')) {
        // 如果是完整的日期时间格式，只保留时间部分
        const timePart = label.split(' ')[1]
        if (timePart) {
          // 返回"小时:分钟"，例如"16:00"
          return timePart.substring(0, 5)
        }
      }
      return label
    case 'day':
      // 处理日数据，例如从 "2025-03-09" 转为 "03-09"
      const dateParts = label.split('-')
      if (dateParts.length >= 3) {
        return `${dateParts[1]}-${dateParts[2]}`
      }
      return label
    case 'month':
      // 处理月数据，例如从 "2025-03" 转为 "2025年03月"
      const monthParts = label.split('-')
      if (monthParts.length >= 2) {
        return `${monthParts[1]}月`
      }
      return label
    case 'year':
      // 处理年数据，保持年份格式
      return label
    default:
      return label
  }
}

// 渲染图表
function renderChart() {
  if (!chartInstance.value) return
  
  const xAxisData = trendData.value.map(item => item.timeLabel)
  const seriesData = trendData.value.map(item => item.usage)
  
  // 根据数据量和类型决定标签显示策略
  let interval = 0
  let rotate = 0
  
  if (timeType.value === 'hour') {
    // 小时数据使用更严格的间隔和旋转
    interval = Math.max(1, Math.floor(xAxisData.length / 12))
    rotate = 45 // 对小时数据也进行旋转
  } else if (xAxisData.length > 12) {
    // 其他数据类型保持原策略
    interval = 'auto'
    if (timeType.value === 'day' && xAxisData.length > 15) {
      rotate = 45
    } else if (timeType.value === 'month') {
      rotate = 30
    }
  }
  
  // 根据时间类型设置不同的tooltip格式器
  let tooltipFormatter = function(params) {
    // 当trigger为'item'时，params是单个对象而不是数组
    const dataIndex = params.dataIndex
    const originalLabel = xAxisData[dataIndex]
    const value = params.value
    
    let formattedLabel = originalLabel
    if (timeType.value === 'hour') {
      // 为小时数据显示更友好的格式：2025-03-09 16:00
      const dateParts = originalLabel.split(' ')
      if (dateParts.length >= 2) {
        formattedLabel = `${dateParts[0]} ${dateParts[1].substring(0, 5)}`
      }
    }
    
    return `<div style="padding: 3px 6px;">
      <div style="margin-bottom: 3px;font-weight:bold;">${formattedLabel}</div>
      <div>用电量: <span style="float:right;font-weight:bold;margin-left:15px;">${value} KW·h</span></div>
    </div>`
  }
  
  const option = {
    tooltip: {
      trigger: 'item',  // 改为item，使其只在鼠标悬停到数据点时触发
      axisPointer: {
        type: 'shadow'
      },
      formatter: tooltipFormatter,
      backgroundColor: 'rgba(255, 255, 255, 0.9)',
      borderColor: '#ddd',
      borderWidth: 1,
      textStyle: {
        color: '#333'
      },
      extraCssText: 'box-shadow: 0 0 8px rgba(0, 0, 0, 0.1);'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%', // 增加更多底部空间用于旋转的标签
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: xAxisData,
      axisTick: {
        alignWithLabel: true
      },
      axisLabel: {
        interval: interval,
        rotate: rotate,
        formatter: function(value) {
          return formatAxisLabel(value, timeType.value)
        },
        margin: 15, // 增加标签与轴线的距离
        textStyle: {
          fontSize: 11 // 小一号字体，减少重叠
        }
      }
    },
    yAxis: {
      type: 'value',
      name: '电量(KW·h)',
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      }
    },
    series: [{
      name: '用电量',
      type: 'bar',
      barWidth: timeType.value === 'hour' ? '50%' : '60%',
      data: seriesData,
      itemStyle: {
        color: '#1ABC9C'
      },
      emphasis: {
        itemStyle: {
          // 鼠标悬停时的样式
          color: '#16a085'
        }
      },
      // 在柱状图顶部显示数据标签
      label: {
        show: seriesData.length <= 10,  // 当数据点少于10个时显示数据标签
        position: 'top',
        formatter: '{c} KW·h',
        color: '#666'
      }
    }]
  }
  
  chartInstance.value.setOption(option)
}

// 调整图表大小
function resizeChart() {
  chartInstance.value && chartInstance.value.resize()
}

onMounted(() => {
  initChart()
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeChart)
  chartInstance.value && chartInstance.value.dispose()
})
</script>

<style scoped>
.electricity-trend-card {
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title {
  font-size: 16px;
  font-weight: bold;
  display: flex;
  align-items: center;
}

.title .el-icon {
  margin-left: 5px;
  font-size: 14px;
  color: #909399;
}

.chart-container {
  position: relative;
  height: 300px;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.7);
}
</style> 